package com.wbao.dianniu.im;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.mobileim.YWIMKit;
import com.alibaba.mobileim.conversation.IYWConversationService;
import com.alibaba.mobileim.conversation.YWConversation;
import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshBase.Mode;
import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshBase.OnRefreshListener;
import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshListView;
import com.wbao.dianniu.R;
import com.wbao.dianniu.data.NoticeActData;
import com.wbao.dianniu.listener.INoticeActListListener;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.manager.ActivityHelperManager;
import com.wbao.dianniu.manager.ActivityHelperManager.IActivityHelperListener;
import com.wbao.dianniu.manager.NoticeActListManager;
import com.wbao.dianniu.ui.ActivityDetail;
import com.wbao.dianniu.ui.BaseActivity;
import com.wbao.dianniu.ui.SignUpManagerActivity;
import com.wbao.dianniu.utils.PictureDownloadUtils;

/**
 * 活动小助手
 * 
 * @author yejianjun
 *
 */
public class ActivityHelperActivity extends BaseActivity implements INoticeActListListener,IActivityHelperListener {
	private PullToRefreshListView pullListView;
	private ListView mListView;
	private NoticeActListManager manager;
	private MyAdapter adapter;
	private List<NoticeActData> mList;
	private final int PAGE_COUNTS = 10;
	private int currentPage = 0;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentLayout(R.layout.activitys_helper);
		setTitleName("活动小助手");
		init();
		requestData(currentPage);
		ActivityHelperManager.getInstance().addListener(this);
		YWIMKit iMkit = LoginSampleHelper.getInstance().getIMKit();
		IYWConversationService conversationService = iMkit.getConversationService();
		YWConversation conversation = conversationService.getConversationByUserId("116", LoginSampleHelper.APP_KEY);
		if(null != conversation)
			conversationService.markReaded(conversation);
	}
	
	private void init() {
		pullListView = (PullToRefreshListView) findViewById(R.id.agent_listview);
		pullListView.setMode(Mode.PULL_UP_TO_REFRESH);
		pullListView.setOnRefreshListener(onRefreshListener);
		mListView = pullListView.getRefreshableView();
		registerForContextMenu(mListView);
		
		adapter = new MyAdapter(this);
		mList = new ArrayList<NoticeActData>();
		adapter.addData(mList);
		mListView.setAdapter(adapter);
	}
	OnRefreshListener onRefreshListener = new OnRefreshListener() {

		@Override
		public void onRefresh() {
			// 上拉刷新 加载请求数据
			pullUpRequest();
		}
	};
	
	// 上拉刷新数据请求
	private void pullUpRequest(){
		//没有搜索结果 或者数据为空 上拉没有效果
		++currentPage ;
		requestData(currentPage);
	}
	private void requestData(int page) {
		manager = new NoticeActListManager(this);
		manager.addNoticeActListListener(this);
		manager.noticeActList(GlobalContext.accountId, page * PAGE_COUNTS,PAGE_COUNTS);
	}
	
	class MyAdapter extends BaseAdapter{

		private Context mContext;
		private List<NoticeActData> list;
		private LayoutInflater mInflater;
		private final int TYPE_NEED_PENDING = 1;
		private final int TYPE_CHEEK =2;
		private final int TYPE_TEXT = 3;
		private final int TYPE_ALREADY = 4;
		public MyAdapter(Context context) {
			mContext = context;
			mInflater = LayoutInflater.from(mContext);
			if (null == list)
				list = new ArrayList<NoticeActData>();
		}
		
		public void addData(List<NoticeActData> addList){
			for (int i = 0; i < addList.size(); i++) {
				this.list.add(addList.get(i));
			}
		}
		public List<NoticeActData> getList() {
			return list;
		}
		@Override
		public int getCount() {
			if (null == list)
				return 0;
			else
				return list.size();
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			Holder holder = null;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.activity_helper_msg_item, null);   
				holder = new Holder();
				holder.time =  (TextView)convertView.findViewById(R.id.act_user_time);
				holder.content =  (TextView)convertView.findViewById(R.id.act_user_content);
				holder.head = (ImageView)convertView.findViewById(R.id.act_user_head);
				holder.name =  (TextView)convertView.findViewById(R.id.act_user_name);
				holder.label = (TextView) convertView.findViewById(R.id.act_user_label);
				holder.toPend = (Button) convertView.findViewById(R.id.pending_button);
				holder.pendingRl = (RelativeLayout) convertView.findViewById(R.id.notice_act_rl);
				holder.title = (TextView) convertView.findViewById(R.id.notice_act_title);
				holder.checkDetails = (TextView) convertView.findViewById(R.id.act_check_details);
				convertView.setTag(holder); 
			}else{
				 holder = (Holder) convertView.getTag();   
			}
			final NoticeActData data = list.get(position);
			holder.time.setText(data.getCreateDate() == null ? "" : data.getCreateDate());
			holder.content.setText(data.getContent() == null ? "" : data.getContent());
			int status = data.getStatus();
			if(TYPE_NEED_PENDING == status){
				holder.pendingRl.setVisibility(View.VISIBLE);
				holder.checkDetails.setVisibility(View.GONE);
				holder.title.setText(getResources().getString(R.string.enrollment_notification));
				PictureDownloadUtils.displayHeadImage(mContext,holder.head, data.getHeadPic());
				holder.name.setText(data.getRealName() ==null ? "" : data.getRealName() );
				holder.label.setText(data.getLabel() == null ? "" : data.getLabel());
				holder.toPend.setText(getResources().getString(R.string.to_pending));
				holder.toPend.setTextColor(getResources().getColor(R.color.head_name_color));
				holder.toPend.setBackgroundResource(R.drawable.blue_button_bg);
				holder.toPend.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// 跳转到用户头像
						Intent intent = new Intent();
						intent.putExtra(GlobalContext.BUNDLE_ID, data.getActivityId());
						intent.setClass(mContext, SignUpManagerActivity.class);
						startActivity(intent);
					}
				});
			}else if(TYPE_CHEEK == status){
				holder.pendingRl.setVisibility(View.GONE);
				holder.checkDetails.setVisibility(View.VISIBLE);
				holder.title.setText(getResources().getString(R.string.enrollment_feedback));
				holder.checkDetails.setOnClickListener(new DetailClickListener(data.getActivityId()));
			}else if(TYPE_TEXT == status){
				holder.pendingRl.setVisibility(View.GONE);
				holder.checkDetails.setVisibility(View.GONE);
				holder.title.setText(getResources().getString(R.string.enrollment_feedback));
			}else if(TYPE_ALREADY == status){
				holder.pendingRl.setVisibility(View.VISIBLE);
				holder.checkDetails.setVisibility(View.GONE);
				holder.title.setText(getResources().getString(R.string.enrollment_notification));
				PictureDownloadUtils.displayHeadImage(mContext,holder.head, data.getHeadPic());
				holder.name.setText(data.getRealName() ==null ? "" : data.getRealName() );
				holder.label.setText(data.getLabel() == null ? "" : data.getLabel());
				holder.toPend.setText(getResources().getString(R.string.already_pending));
				holder.toPend.setTextColor(getResources().getColor(R.color.gray_text));
				holder.toPend.setBackgroundColor(getResources().getColor(R.color.transparent));
				holder.toPend.setClickable(false);
			}
			
			return convertView;
		}
		
		private class DetailClickListener implements OnClickListener{
			
			private int activityId;
			public DetailClickListener(int activityId) {
				// TODO Auto-generated constructor stub
				this.activityId = activityId;
			}
			
			@Override
			public void onClick(View v) {
				switch (v.getId()) {
				case R.id.act_check_details:
					Intent rightIntent = new Intent();
					rightIntent.putExtra(GlobalContext.INTENT_ACTIVITYID, activityId);
					rightIntent.setClass(mContext, ActivityDetail.class);
					startActivity(rightIntent);
					break;
				default:
					break;
				}
			}
			
			
		}
		
		public boolean removeOneList(int activityId , int accountId){
			boolean ret = false;
			for (int i = 0; i < list.size(); i++) {
				if(activityId == list.get(i).getActivityId() && accountId == list.get(i).getAccountId()){
					ret = true;
					list.remove(i);
					notifyDataSetChanged();
					break;
				}
			}
			return ret;
		}
		class Holder{
			public TextView time;
			public TextView content;
			public ImageView head;
			public TextView name;
			public TextView label;
			public Button toPend;
			public TextView title;
			public RelativeLayout pendingRl;
			public TextView checkDetails;
		}
		
	}

	@Override
	public void onNoticeActListFailure(int errorCode, String errorMsg) {
		pullListView.onRefreshComplete(false, false);
	}

	@Override
	public void onNoticeActListSuccess(List<NoticeActData> list) {
		pullListView.onRefreshComplete(false, false);
		if(null == list)
			return;
		adapter.addData(list);
		mList = adapter.getList();
		adapter.notifyDataSetChanged();
	}

	@Override
	public void statusChanged(int activityId, int accountId, int status) {
		// TODO Auto-generated method stub
		for (int i = 0; i < mList.size(); i++) {
			if(activityId == mList.get(i).getActivityId() && accountId == mList.get(i).getAccountId()){
				mList.get(i).setStatus(status);
				adapter.notifyDataSetChanged();
				break;
			}
		}
		
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		ActivityHelperManager.getInstance().removeListener(this);
	}
	
}
